package edu.xpu.project.user.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.xpu.project.user.entity.CourseType;
import edu.xpu.project.user.repository.CourseTypeRepository;

@Service
@Transactional(readOnly=true)
public class CourseTypeServiceImpl implements CourseTypeService {
	
	@Autowired
	private CourseTypeRepository courseTypeRepository;

	@Override
	public CourseType get(Long id) {
		return courseTypeRepository.findOne(id);
	}

	@Transactional(readOnly=false)
	@Override
	public CourseType saveOrUpdate(CourseType t) {
		CourseType saveAndFlush = courseTypeRepository.saveAndFlush(t);
		return saveAndFlush;
	}

	@Transactional(readOnly=false)
	@Override
	public void delete(Long id) {
		courseTypeRepository.delete(id);
	}

	@Override
	public Page<CourseType> getPageByCriterias(String pageNumberStr, String pageSizeStr, final CourseType courseType) {
		Integer pageNumber = 1;
		Integer pageSize = 10;
		try {
			pageNumber = Integer.parseInt(pageNumberStr);
		} catch (Exception e) {}
		try {
			pageSize = Integer.parseInt(pageSizeStr);
		} catch (Exception e) {}
		Pageable pageable = new PageRequest(pageNumber - 1, pageSize);
		
		return courseTypeRepository.findAll(new Specification<CourseType>() {
			@Override
			public Predicate toPredicate(Root<CourseType> root, CriteriaQuery<?> query,
					CriteriaBuilder builder) {
				if (courseType == null) {
					return null;
				}
				//添加查询条件
				List<Predicate> predicates = new ArrayList<Predicate>(3);
				
				if (predicates.size() == 0) {
					return null;
				}
				Predicate[] predArr= new Predicate[predicates.size()];
				return builder.and(predicates.toArray(predArr));
			}
		}, pageable);
	}

	@Override
	public CourseType getByCourseName(String courseName) {
		List<CourseType> findByCourseName = courseTypeRepository.findByCourseName(courseName);
		if (findByCourseName != null && findByCourseName.size() != 0) {
			return findByCourseName.get(0);
		}
		return null;
	}

}
